package cn.aitstone.filter;

import cn.aitstone.constants.FilterConstants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /*
    * 数字越小，优先级越高
    */
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {

        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("/register") || uri.endsWith("/login") || uri.contains("/static/")){
            return false;
        }

        return true;
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token) && isTokenTrue()){
            Map<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("message", "nologin");
            map.put("code", 402);
            String result = JSON.toJSONString(map);
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(402);
            try {
                response.getWriter().print(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }

        return null;
    }

    private boolean isTokenTrue(){
        return true;
    }
}
